﻿/*----------------------------------------------------------------
 * 
 * 版权所有：Copyright (C) 2013
 * 
 * 文件名：OrderByHelper.cs
 * 文件功能描述：
 * 
 * 
 * 作 者：zhangq
 * 邮 箱：ifunnyface@outlook.com
 * 日 期：2013-01-08 09:29:42
 * 
 * 
 * 修改标识： Author
 * 修改描述： 相关描述
 * 
 * ---------------------------------------------------------------- */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Common.Extensions.OrderBy
{

    /// <summary>
    /// Entity Framework 排序扩展
    /// </summary>
    public static class OrderByHelper
    {


        /// <summary>
        /// 多字段排序
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="query">IQueryable</param>
        /// <param name="orderByExpressions">排序规则</param>
        /// <returns>IQueryable</returns>
        public static IQueryable<TEntity> OrderBy<TEntity>(this IQueryable<TEntity> query,
            params IOrderByExpression<TEntity>[] orderByExpressions) where TEntity : class
        {
            if (orderByExpressions == null)
                return query;

            IOrderedQueryable<TEntity> output = null;

            foreach (var orderByExpression in orderByExpressions)
            {
                if (output == null)
                {
                    output = orderByExpression.ApplyOrderBy(query);
                }
                else
                {
                    output = orderByExpression.ApplyThenBy(output);
                }
            }

            return output ?? query;
        }


    }

}